package com.bi.bitest.bao.utils;

import java.io.IOException;
import java.lang.ref.SoftReference;
import java.util.HashMap;
import java.util.Map;
import android.content.Context;
import android.graphics.Bitmap;
import android.support.v4.util.LruCache;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.Volley;

public class VolleyUtils {

	public static RequestQueue mQueue;
	public static ImageLoader mLoader;
	
	private static LruCache<String,Bitmap> lruCache;
	private static Map<String,SoftReference<Bitmap>> softCache;
	
	
	public static RequestQueue getQueue(Context context){
		if(mQueue==null){
			mQueue=Volley.newRequestQueue(context);
		}
		
		return mQueue;
	}
	
	public static ImageLoader getLoader(Context context){
		if(mLoader==null){
			softCache=new HashMap<String, SoftReference<Bitmap>>();

			lruCache=new LruCache<String, Bitmap>(2*1024*1024){
				@Override
				protected int sizeOf(String key, Bitmap value) {

					return value.getRowBytes()*value.getHeight();
				}
				
				@Override
				protected void entryRemoved(boolean evicted, String key,
						Bitmap oldValue, Bitmap newValue) {
					if(evicted)
						softCache.put(key, new SoftReference<Bitmap>(oldValue));
					
					super.entryRemoved(evicted, key, oldValue, newValue);
				}
			};
			
			mLoader=new ImageLoader(getQueue(context), new ImageLoader.ImageCache() {
				
				@Override
				public void putBitmap(String url, Bitmap bitmap) {

					lruCache.put(url, bitmap);

					/*try {
				ImageUtils.saveImg(url, bitmap);
					} catch (IOException e) {
						e.printStackTrace();
					}*/
				}
				
				
				@Override
				public Bitmap getBitmap(String url) {
					Bitmap b=lruCache.get(url);
					if(b==null){

						SoftReference<Bitmap> reference=softCache.get(url);
						if(reference!=null){
							b=reference.get();
							if(b!=null){
								lruCache.put(url, b);
								softCache.remove(reference);
							}
						}else{
						//	b=ImageUtils.getImg(url);
							if(b!=null){
								lruCache.put(url, b);
							}
						}
					}
					return b;
				}
			});
		}
		
		return mLoader;
	}
	
}
